/*
 * module.c
 *
 * Copyright (C) 2018 Aleksandar Andrejevic <theflash@sdf.lonestar.org>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <module.h>
#include <exec/elf.h>
#include <memory.h>

extern dword_t load_module_elf(const void *address, module_t *module);

typedef dword_t (*driver_load_proc_t)(const char *parameters);

char driver_name[] = "kernel";
static DECLARE_LIST(modules);

module_t *get_module_from_address(void *address)
{
    uintptr_t addr = (uintptr_t)address;

    list_entry_t *i, *j;
    for (i = modules.next; i != &modules; i = i->next)
    {
        module_t *module = CONTAINER_OF(i, module_t, link);

        for (j = module->segments.next; j != &module->segments; j = j->next)
        {
            module_segment_t *segment = CONTAINER_OF(j, module_segment_t, link);
            if (addr >= (uintptr_t)segment->address && addr < ((uintptr_t)segment->address + segment->size)) return module;
        }
    }

    return NULL;
}

dword_t module_load_from_physical(module_t *module, const char *parameters)
{
    module->name = NULL;
    module->load_proc = NULL;
    module->unload_proc = NULL;
    list_init(&module->segments);

    area_t area = {
        .pages = memory_find_page_by_address(module->physical_address),
        .count = PAGE_NUMBER(PAGE_ALIGN_UP(module->size))
    };
    void *address = NULL;
    sysret_t ret = memory_view_area(memory_upper_space, &address, &area, MEMORY_FLAG_ACCESSIBLE);
    if (ret != ERR_SUCCESS) return ret;

    ret = load_module_elf(address, module);
    if (ret != ERR_SUCCESS) goto cleanup;

    if (!module->name)
    {
        // TODO
        return ERR_INVALID;
    }

    ret = module->load_proc(parameters);
    if (ret != ERR_SUCCESS)
    {
        // TODO
        return ret;
    }

    list_append(&modules, &module->link);

cleanup:
    memory_free(memory_upper_space, address);
    return ret;
}

dword_t module_unload(module_t *module)
{
    return ERR_NOSYSCALL; // TODO
}
